<style>
.pure_table_extra { width: 700px; margin-top: 5px; }
.pure_table_extra th { height: 25px; line-height: 25px; }
.pure_table_extra td { vertical-align: middle; }
.pure_table_extra select { width: 100%; }
</style>

<?php
$PT = PT_NCEA_ENGLISH;

$opts = new stdClass();
$opts->cd = 't.type = :v1';
$opts->cdv = array(':v1' => $PT);
$data = $orm->get('pb_colg_class', 't.name', 'ASC', NULL, NULL, $opts)->d;
foreach ($data as $itm) {
  $itm->times = json_decode($itm->times);
}
$teachers = $orm->get('pb_colg_teacher', 't.first_name', 'ASC', NULL, NULL, NULL)->d;
$classrooms = $orm->get('pb_colg_classroom', 't.name', 'ASC', NULL, NULL, NULL)->d;
?>

<div class="pure-form">
  <input id="new_name" type="text" placeholder="{Class Name}" onkeypress="if(event.which == 13) add_obj();" />
  <select id="new_teacher"><option value="0">Choose a teacher...</option></select>
  <select id="new_classroom"><option value="0">Choose a classroom...</option></select>
  <button type="submit" class="pure-button pure-button-primary" onclick="add_obj();">Add</button>
</div>
<table class="pure-table pure_table_extra" cellpadding=0 cellspacing=0>
  <thead id="data_head">
    <tr>
      <th class="ui-widget-header" style="width: 120px;">Name</th>
      <th class="ui-widget-header" style="width: 120px;">Teacher</th>
      <th class="ui-widget-header" style="width: 120px;">Classroom</th>
      <th class="ui-widget-header">Time</th>
      <th class="ui-widget-header" style="width: 40px;">&nbsp;</th>
    </tr>
  </thead>
  <tbody id="data_body"></tbody>
</table>
<div>&nbsp;</div>
<div id="timetable"></div>

<div id="dialog_change" class="pure-form" style="display: none;" title="Change Name">
  <input type="text" id="name_change" style="width: 100%;"></input>
</div>

<div id="dialog_tt" class="pure-form" style="display: none;">
  <div id="class_tt"></div>
  <input type="text" id="start_tt" />&nbsp;<input type="text" id="end_tt" />
</div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __teachers = JSON.parse('<?php echo addslashes(json_encode($teachers)); ?>');
  var __classrooms = JSON.parse('<?php echo addslashes(json_encode($classrooms)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __type = '<?php echo $PT; ?>';
  
  $(function() {
    reset();
    for (var idx in __teachers) {
      var itm = __teachers[idx];
      $('#new_teacher').append('<option value="' + itm.id + '">' + itm.first_name + ' ' + itm.last_name + '</option>');
    }
    for (var idx in __classrooms) {
      var itm = __classrooms[idx];
      $('#new_classroom').append('<option value="' + itm.id + '">' + itm.name + '</option>');
    }
    
    render();
  });

  function reset() {
    __data = __data.sort(function(a, b) {
      return a.name.localeCompare(b.name);
    });
  };

  function render() {
    $('#new_name').val('');
    $('#new_teacher').val(0);
    $('#new_classroom').val(0);
    
    $('#timetable').empty();
    $('#timetable').fullCalendar({
      defaultView: 'agendaWeek',
      header: {
        left: '',
        center: '',
        right: ''
      },
      columnFormat: {
        week: 'ddd'
      },
      year: 2000,
      month: 0,
      date: 3,
      allDaySlot: false,
      height: 800,
      weekends: false,
      theme: true,
      
      minTime: 9,
      maxTime: 23,
      
      timeFormat: 'HH:mm{-HH:mm}',

      editable: true,
      selectable: true,

      eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc) {
        event.__obj.times[event.__idx] = $.fullCalendar.formatDate(event.start, 'yyyy-MM-dd HH:mm') + '#' + $.fullCalendar.formatDate(event.end, 'yyyy-MM-dd HH:mm');
        Ajax.request(
          __requrl + 'submit_obj',
          'req=' + Utils.encodeURI(JSON.stringify(event.__obj)),
          function(rslt) {
            render_data();
          },
          null
        );
      },

      eventResize: function(event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view) {
        event.__obj.times[event.__idx] = $.fullCalendar.formatDate(event.start, 'yyyy-MM-dd HH:mm') + '#' + $.fullCalendar.formatDate(event.end, 'yyyy-MM-dd HH:mm');
        Ajax.request(
          __requrl + 'submit_obj',
          'req=' + Utils.encodeURI(JSON.stringify(event.__obj)),
          function(rslt) {
            render_data();
          },
          null
        );
      },

      eventClick: function(event, jsEvent, view) {
        change_time(event.__obj.id, event.__idx, jsEvent, null, null);
      },

      select: function(start, end, allDay) {
        change_time(0, -1, null, $.fullCalendar.formatDate(start, 'yyyy-MM-dd HH:mm'), $.fullCalendar.formatDate(end, 'yyyy-MM-dd HH:mm'));
      },

      events: function(start, end, callback) {
        for(var idx in __data) {
          var itm = __data[idx];
          for (var idx2 in itm.times) {
            var itm2 = itm.times[idx2];
            var rslt = itm2.split('#');
            var evt = {
              __obj: itm,
              __idx: idx2,
              start: rslt[0] + ':00',
              end: rslt[1] + ':00',
              allDay: 0,
              title: itm.name + ((itm.room_id == 0) ? '' : itm.room_name) + ((itm.teacher_id == 0) ? '' : '\n' + itm.teacher_name),
              description: ''
            };
            $("#timetable").fullCalendar('renderEvent', evt, true);
          }
        }
      }
    });
    render_data();
  };
  
  function render_data() {
    $('#data_body').empty();
    for (var idx in __data) {
      var itm = __data[idx];
      $('#data_body').append(
        '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
          '<td><a href="#" onclick="change_name(' + itm.id + ', event);">' + itm.name + '</a></td>' +
          '<td><select id="teacher_' + itm.id + '" onchange="update_teacher(' + itm.id + ', this);"><option value="0">&nbsp;</option></select></td>' +
          '<td><select id="classroom_' + itm.id + '" onchange="update_classroom(' + itm.id + ', this);"><option value="0">&nbsp;</option></select></td>' +
          '<td>' + get_times(itm.times) + '</td>' +
          '<td>' +
            '<span style="cursor: pointer; float: left;" class="ui-button-icon-primary ui-icon ui-icon-closethick" onclick="delete_obj(' + itm.id + ');"></span>' +
          '</td>' + 
        '</tr>'
      );
      for (var idx2 in __teachers) {
        var itm2 = __teachers[idx2];
        $('#teacher_' + itm.id).append('<option value="' + itm2.id + '"' + ((itm2.id == itm.teacher_id) ? 'selected="selected"' : '') + '>' + itm2.first_name + ' ' + itm2.last_name + '</option>');
      }
      for (var idx2 in __classrooms) {
        var itm2 = __classrooms[idx2];
        $('#classroom_' + itm.id).append('<option value="' + itm2.id + '"' + ((itm2.id == itm.room_id) ? 'selected="selected"' : '') + '>' + itm2.name + '</option>');
      }
    }
    if (__data.length == 0) {
      $('#data_body').append('<tr class="pure-table-even"><td colspan=' + $('#data_head tr').children('th').length + '>None</td></tr>');
    }
  };

  function get_times(times) {
    var str = '';
    for (var idx in times) {
      var itm = times[idx];
      var rslt = itm.split('#');
      var ds = rslt[0].split(' ')[0].split('-');
      var d = new Date(ds[0], ds[1] - 1, ds[2]);
      str += ((str == '') ? '' : ', ');
      str += Utils.get_weekday(d.getDay()) + ' ' + rslt[0].split(' ')[1] + '-' + rslt[1].split(' ')[1];
    }
    return str;
  };
  
  function delete_obj(id) {
    var req = Utils.get_by_id(id, __data);
    Ajax.request(
      __requrl + 'delete_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        Utils.splice_by_id(id, __data);
        reset();
        render();
      },
      { confirm: 1 }
    );
  };

  function update_teacher(id, elm) {
    var req = Utils.get_by_id(id, __data);
    req.teacher_id = elm.options[elm.selectedIndex].value;
    req.teacher_name = elm.options[elm.selectedIndex].text;
    
    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        reset();
        render();
      },
      null
    );
  };

  function update_classroom(id, elm) {
    var req = Utils.get_by_id(id, __data);
    req.room_id = elm.options[elm.selectedIndex].value;
    req.room_name = elm.options[elm.selectedIndex].text;
    
    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        reset();
        render();
      },
      null
    );
  };

  function add_obj() {
    var req = {
      type: __type,
      name: $('#new_name').val(),
      teacher_id: $('#new_teacher option:selected').val(),
      teacher_name: $('#new_teacher option:selected').text(),
      room_id: $('#new_classroom option:selected').val(),
      room_name: $('#new_classroom option:selected').text(),
      times: [ '2000-01-03 09:00#2000-01-03 11:00', '2000-01-03 09:00#2000-01-03 11:00', '2000-01-04 09:00#2000-01-04 11:00', '2000-01-05 09:00#2000-01-05 11:00', '2000-01-06 09:00#2000-01-06 11:00' ]
    };
    Ajax.request(
      __requrl + 'submit_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data[__data.length] = rslt;
        reset();
        render();
      },
      null
    );
  };

  function change_name(id, ev) {
    var func = function() {
      var req = Utils.get_by_id(id, __data);
      req.name = $('#name_change')[0].value;
      Ajax.request(
        __requrl + 'submit_obj',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          reset();
          render();
          $('#dialog_change').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_change').dialog({
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });

    var obj = Utils.get_by_id(id, __data);
    
    $('#name_change')[0].onkeypress = function(ev) {
      if(ev.which == 13) {
        func();
      }
    };
    $('#name_change').val(obj.name);
    $('#name_change').select();
  };

  function change_time(id, index, ev, start, end) {
    var func = function() {
      if (id == 0) {
        id = $('#newclass_tt option:selected').val();
      }
      var req = Utils.get_by_id(id, __data);
      if (index == -1) {
        req.times[req.times.length] = start.split(' ')[0] + ' ' + $('#start_tt').val() + '#' + end.split(' ')[0] + ' ' + $('#end_tt').val();
      } else {
        req.times[index] = rslt[0].split(' ')[0] + ' ' + $('#start_tt').val() + '#' + rslt[0].split(' ')[0] + ' ' + $('#end_tt').val();
      }
      Ajax.request(
        __requrl + 'submit_obj',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          reset();
          render();
          $('#dialog_tt').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_tt').dialog({
      position: {
        my: 'left+0 bottom+0',
        of: ev ? ev.target : $('#timetable')
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });
    
    if (id == 0) {
      $('#start_tt').val(start.split(' ')[1]);
      $('#end_tt').val(end.split(' ')[1]);
      $('#class_tt').html('<select id="newclass_tt"></select><div>&nbsp;</div>');
      for (var idx in __data) {
        var itm = __data[idx];
        $('#newclass_tt').append('<option value="' + itm.id + '">' + itm.course_name + ' ' + itm.name + '</option>');
      }
    } else {
      $('#dialog_tt').dialog('option', 'buttons', {
        'OK': function() {
          func();
        },
        'Delete': function() {
          var req = Utils.get_by_id(id, __data);
          req.times.splice(index, 1);
          Ajax.request(
            __requrl + 'submit_obj',
            'req=' + Utils.encodeURI(JSON.stringify(req)),
            function(rslt) {
              reset();
              render();
              $('#dialog_tt').dialog('close');
            },
            null
          );
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      });
      
      var obj = Utils.get_by_id(id, __data);
      var rslt = obj.times[index].split('#');
      $('#start_tt').val(rslt[0].split(' ')[1]);
      $('#end_tt').val(rslt[1].split(' ')[1]);
      $('#class_tt').html('<h3>' + obj.course_name + ' ' + obj.name + '</h3>');
    }
    $('#start_tt').timepicker({ 'step': 5, 'timeFormat': 'H:i', 'scrollDefaultTime': true });
    $('#end_tt').timepicker({ 'step': 5, 'timeFormat': 'H:i', 'scrollDefaultTime': true });
  };
  /*]]>*/
</script>